<?php 
namespace app\admin\controller;

use think\Exception;
use think\Db;
use app\common\model\CompanyNotice;
use app\common\model\CompanyNoticeRead;
use app\common\controller\Richtext;
use app\common\model\CompanyStaff;
use app\common\controller\Wechat;

class Notice extends Base
{
	/**
	 * 添加公告
	 * @throws Exception
	 */
	public function addNotice()
	{
		$data = $this->request->param('');
		Db::startTrans();
		try {
			if(!$data['title'])throw new Exception('请输入公告标题');
			if(!$data['content']) throw new Exception('请输入公告内容');
			$data['create_time'] = time();
			$data['sender'] = '微联管理员';
			$res = CompanyNotice::create($data);
			//添加公告阅读数据
			$info = [
					'notice_id' => $res->id,
					'reader' => '[]',
					'create_time' => time(),
			];
			CompanyNoticeRead::create($info);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return $this->error($e->getMessage ());
		}
		// 给用户公众号推送消息
		$staff_list = CompanyStaff::where(['leave_state' => 1])->column('openid');
		foreach ($staff_list as $rows) {
			if(!$rows)continue;
			$tmep_data = [
					"first" => [
							"value" => $data['title'],
							"color" => "#000000"
					],
					"keyword1" => [
							"value" => Richtext::getStirng($data['content'], 30),
							"color" => "#173177"
					],
					"keyword2" => [
							"value" => date("Y/m/d H:i"),
							"color" => "#333333"
					],
					"remark" => [
							"value" => "请仔细阅读，恐有遗漏~",
							"color" => "#333333"
					]
			];
			Wechat::modelMsg($rows, 'PxE0jWSEr1IVHn5-ja42EX1nQMcMuaxDkx445jRSdk4', $tmep_data,'https://www.gsmjb.com');
		}
		
		return $this->success('添加公告');
	}
	
	/**
	 * 公告列表
	 */
	public function noticeList()
	{
		$list = CompanyNotice::where(['state' => 1])->order('id desc')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['content1'] = Richtext::getStirng($rows['content'], 100);
		}
		return $this->success($list);
	}
	
	/**
	 * 删除公告
	 * @throws Exception
	 */
	public function deleteNotice()
	{
		$id = $this->request->param('id');
		try {
			$notice = CompanyNotice::get($id);
			if(!$notice->state)throw new Exception('状态错误');
			$notice->save(['state' => 0]);
		} catch (Exception $e) {
			return $this->error($e->getMessage());
		}
		return $this->success('删除成功');
	}
}